//
//  WCBShaixuCell.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/15.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBShaixuCell.h"
#import "ActionSheetStringPicker.h"
#import "WCBDataHelper.h"
#import "NSDate+TFCore.h"

static NSString *kWCBShaixuNotification = @"kWCBShaixuNotification";

@interface WCBShaixuCell()
@property (strong, nonatomic) UIButton *selectButton;

@property (strong, nonatomic) UIView *dateRangeView;
@property (strong, nonatomic) WCBSelectField *startButton;
@property (strong, nonatomic) WCBSelectField *endButton;

@property (strong, nonatomic) NSArray *allMonth;
@end

@implementation WCBShaixuCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.contentView.backgroundColor = [UIColor whiteColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification:) name:kWCBShaixuNotification object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Public
- (void)setModel:(WCBShaixuModel *)model
{
    _model = model;
    
    if (!model.custom) {
        [self.selectButton setTitle:[NSString stringWithFormat:@"只做%@年的内容", model.startDesc] forState:UIControlStateNormal];
        [self.selectButton setTitle:[NSString stringWithFormat:@"只做%@年的内容", model.startDesc] forState:UIControlStateSelected];
        if (self.dateRangeView.superview) {
            [self.dateRangeView removeFromSuperview];
        }
    }
    else {
        [self.selectButton setTitle:@"自定义时间" forState:UIControlStateNormal];
        [self.selectButton setTitle:@"自定义时间" forState:UIControlStateSelected];
        [self.contentView addSubview:self.dateRangeView];
        
        [self.startButton setTitle:model.startDesc];
        [self.endButton setTitle:model.endDesc];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat x, y, w, h;
    CGFloat width = CGRectGetWidth(self.contentView.frame);
    
    {
        x = 20.f;
        y = 10;
        w = width - 2 * x;
        h = 40.f - 2 * y;
        self.selectButton.frame = CGRectMake(x, y, w, h);
    }
    
    if (self.model.custom) {
        x = 0;
        y = CGRectGetMaxY(self.selectButton.frame) + 10;
        w = width;
        h = 50.f;
        self.dateRangeView.frame = CGRectMake(x, y, w, h);
    }
}

#pragma mark - Actions
- (void)selectDidClick
{
    self.selectButton.selected = !self.selectButton.selected;
    self.model.selected = self.selectButton.selected;
    [[NSNotificationCenter defaultCenter] postNotificationName:kWCBShaixuNotification object:self.model];
}

- (void)didReceiveNotification:(NSNotification *)noti
{
    id model = noti.object;
    if (model != self.model) {
        self.selectButton.selected = NO;
        self.model.selected = NO;
    }
}

- (void)startDidClick:(UIButton *)btn
{
    NSLog(@"%s", __func__);
    [self showActionSheetWithOrigin:btn];
}

- (void)endDidClick:(UIButton *)btn
{
    NSLog(@"%s", __func__);
    [self showActionSheetWithOrigin:btn];
}

#pragma mark - Private
- (void)showActionSheetWithOrigin:(UIButton *)origin
{
    __weak WCBShaixuCell *weakself = self;
    [ActionSheetStringPicker showPickerWithTitle:@"选择日期"
                                            rows:self.allMonth
                                initialSelection:0
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           [origin setTitle:selectedValue forState:UIControlStateNormal];
                                           
                                           if (origin.tag == weakself.startButton.tag) {
                                               weakself.model.startDesc = selectedValue;
                                               weakself.model.startDate = [weakself startIntervalWithMonth:selectedValue];
                                           }
                                           else {
                                               weakself.model.endDesc = selectedValue;
                                               weakself.model.endDate = [weakself lastIntervalWithMonth:selectedValue];
                                           }
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         
                                     }
                                          origin:origin];
}

- (NSTimeInterval)startIntervalWithMonth:(NSString *)month
{
    NSDate *firstDayDate = [NSDate tf_dateWithDateString:[NSString stringWithFormat:@"%@-01", month] format:@"YYYY-MM-dd"];
    NSDate *lastDayDate = firstDayDate.tf_startDateOfMonth;
    return [lastDayDate timeIntervalSince1970];
}

- (NSTimeInterval)lastIntervalWithMonth:(NSString *)month
{
    NSDate *firstDayDate = [NSDate tf_dateWithDateString:[NSString stringWithFormat:@"%@-01", month] format:@"YYYY-MM-dd"];
    NSDate *lastDayDate = firstDayDate.tf_endDateOfMonth;
    return [lastDayDate timeIntervalSince1970];
}

#pragma mark - Getter
- (NSArray *)allMonth
{
    if (!_allMonth) {
        _allMonth = [WCBDataHelper.sharedHelper getAllMonths];
    }
    return _allMonth;
}

- (UIButton *)selectButton
{
    if (!_selectButton) {
        _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        [_selectButton setImage:[UIImage imageNamed:@"btn_unselect"] forState:UIControlStateNormal];
        [_selectButton setImage:[UIImage imageNamed:@"btn_select"] forState:UIControlStateSelected];
        [_selectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_selectButton setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        _selectButton.titleLabel.font = [UIFont systemFontOfSize:23];
        _selectButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _selectButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [_selectButton addTarget:self action:@selector(selectDidClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_selectButton];
    }
    return _selectButton;
}

- (UIView *)dateRangeView
{
    if (!_dateRangeView) {
        _dateRangeView = [[UIView alloc] init];
        [self.contentView addSubview:_dateRangeView];
        
        _startButton = [[WCBSelectField alloc] init];
        _startButton.tag = 1000;
        [_startButton addTarget:self action:@selector(startDidClick:)];
        [_dateRangeView addSubview:_startButton];
        
        UILabel *to = [[UILabel alloc] init];
        to.textColor = [UIColor blackColor];
        to.font = [UIFont systemFontOfSize:23];
        to.textAlignment = NSTextAlignmentCenter;
        to.text = @"至";
        [_dateRangeView addSubview:to];
        
        _endButton = [[WCBSelectField alloc] init];
        _endButton.tag = 1001;
        [_endButton addTarget:self action:@selector(endDidClick:)];
        [_dateRangeView addSubview:_endButton];
        
        CGFloat x, y, w, h;
        {
            x = 70.f;
            y = 5.f;
            w = 160.f;
            h = 50 - 2 * y;
            _startButton.frame = CGRectMake(x, y, w, h);
        }
        
        {
            x = CGRectGetMaxX(_startButton.frame) + 15.f;
            y = 5.f;
            w = 30.f;
            h = 50 - 2 * y;
            to.frame = CGRectMake(x, y, w, h);
        }
        
        {
            x = CGRectGetMaxX(to.frame) + 15.f;
            y = 5.f;
            w = 160.f;
            h = 50 - 2 * y;
            _endButton.frame = CGRectMake(x, y, w, h);
        }
    }
    return _dateRangeView;
}

@end


@interface WCBSelectField ()
@property (strong, nonatomic) UIButton *titleButton;
@property (strong, nonatomic) UIImageView *arrowImageView;
@end

@implementation WCBSelectField

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.layer.borderColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.95 alpha:1.00].CGColor;
        self.layer.borderWidth = 1.5f;
        
        UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        titleButton.titleLabel.font = [UIFont systemFontOfSize:23];
        titleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self addSubview:titleButton];
        self.titleButton = titleButton;
        
        UIImageView *arrowImageView = [[UIImageView alloc] init];
        arrowImageView.image = [UIImage imageNamed:@"img_expand.png"];
        arrowImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:arrowImageView];
        self.arrowImageView = arrowImageView;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat x, y, w, h;
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat height = CGRectGetHeight(self.frame);
    
    {
        y = 8;
        h = height - 2 * y;
        w = h;
        x = width - w - 15;
        self.arrowImageView.frame = CGRectMake(x, y, w, h);
    }
    
    {
        x = 10.f;
        y = 5.f;
        w = width - CGRectGetWidth(self.arrowImageView.frame);
        h = height - 2 * y;
        self.titleButton.frame = CGRectMake(x, y, w, h);
    }
}

#pragma mark - Public
- (void)addTarget:(id)target action:(SEL)action
{
    [self.titleButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}

- (void)setTitle:(NSString *)title
{
    [self.titleButton setTitle:title forState:UIControlStateNormal];
}

@end
